﻿#!python -u
import sys
sys.path.append('../')
from goAgent import GoAgent
from goEnv import *
from goJudge import *



cols='ABCDEFGHJKLMNOPQRST'

class gtp_client:
	def __init__(self):
		self.commands_mini={
			"protocol_version":self.foo_protocol_version,
			"name":self.foo_name,
			"version":self.foo_version,
			"list_commands":self.foo_list_commands,
			"boardsize":self.foo_boardsize,
			"clear_board":self.foo_clear_board,
			"komi":self.foo_komi,
			"play":self.foo_play,
			"genmove":self.foo_genmove,
		}
		self.agentB=GoAgent(Player.black)
		self.agentW=GoAgent(Player.white)
		self.board=GoBoard()		
	def foo_protocol_version(self,args): #gtp版本
		return '2'
	def foo_name(self,args):
		return 'MyGo'
	def foo_version(self,args): #软件版本
		return '1.0'
	def foo_list_commands(self,args):
		return 'protocol_version\nname\nversion\nlist_commands\nboardsize\nclear_board\nkomi\nplay\ngenmove'
	def foo_boardsize(self,args):
		return '' if args[0] else 'board size outside engine\'s limits'
	def foo_clear_board(self,args):
		self.board=GoBoard()
		return ''
	def foo_komi(self,args):
		return ''
	def foo_play(self,args):		
		if len(args)!=2:
			return 'Unknown command.'
		if args[0].lower()!='b' and args[0].lower()!='black' and args[0].lower()!='w' and args[0].lower()!='white':
			return 'Unknown command.'
		if args[0].lower()=='b' or args[0].lower()=='black':
			whosTurn=Player.black
		else:
			whosTurn=Player.white
		move=self.gtp_position_to_coords(args[1])
		self.board.envUpdate(whosTurn,move)
		self.board.printBoard()
		return ''
	def foo_genmove(self,args):
		if len(args)!=1:
			return 'Unknown command.'
		if args[0].lower()=='b' or args[0].lower()=='black':
			whosTurn=Player.black
		elif args[0].lower()=='w' or args[0].lower()=='white':
			whosTurn=Player.white			
		else:
			return 'Unknown command.'
		if whosTurn==Player.black:
			move=self.agentB.chooseMove('R',self.board)
		else:
			move=self.agentW.chooseMove('R',self.board)
		self.board.envUpdate(whosTurn,move)
		self.board.printBoard()
		return self.coords_to_gtp_position(move)
	
	def coords_to_gtp_position(self,point):
		col,row=(point[0],point[1])
		row_str=cols[row]
		return row_str+str(col+1)

	def gtp_position_to_coords(self,gtp_position):
		col_str,row_str=gtp_position[0],gtp_position[1:]
		point = (int(row_str)-1, cols.find(col_str.upper()))
		return (point)
    
	def run(self):
		while True:
			s=sys.stdin.readline().strip()
			if s.split()[0] in self.commands_mini:
				resp=self.commands_mini[s.split()[0]](s.split()[1:])
				sys.stdout.write('= '+resp+'\n'+'\n')
				sys.stdout.flush()	#如果用pyinstaller编译成exe程序，没有办法实现“#!python -u”命令的效果。

if __name__ == "__main__":
    game = gtp_client()
    game.run()